package com.cms.admin.action.voice;

import com.aliyun.oss.model.PutObjectResult;
import com.cms.admin.action.BaseAction;
import com.cms.admin.model.PageBean;
import com.cms.admin.model.VoiceOnDemond;
import com.cms.admin.model.VoiceOnDemondData;
import com.cms.admin.model.VoiceOnDemondDataExt;
import com.cms.admin.service.common.TemplateService;
import com.cms.admin.service.voice.VoiceService;
import com.cms.admin.util.Constants;
import com.cms.admin.util.FtpClient;
import com.cms.admin.util.PropertiesService;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ModelDriven;
import net.sf.json.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.util.TextUtils;
import org.jaudiotagger.audio.AudioFile;
import org.jaudiotagger.audio.AudioFileIO;
import org.jaudiotagger.audio.AudioHeader;
import org.jaudiotagger.audio.exceptions.CannotReadException;
import org.jaudiotagger.audio.exceptions.InvalidAudioFrameException;
import org.jaudiotagger.audio.exceptions.ReadOnlyFileException;
import org.jaudiotagger.tag.TagException;

import java.io.*;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by YYY-Work on 2017/7/17.
 */
public class VoiceAction extends BaseAction implements ModelDriven<VoiceOnDemondDataExt> {

    private static Log log = LogFactory.getLog(VoiceAction.class);

    private VoiceService voiceService;
    private TemplateService templateService;
    private VoiceOnDemondDataExt search = new VoiceOnDemondDataExt();
    private PageBean page;
    private VoiceOnDemond voiceOnDemond;


    public String ajaxQueryVoiceDataList() {
        LOG.info("Start ArticleAction process,method is ajaxQuery");
        LOG.debug("Action is:" + search.getAction());

        page = new PageBean(search.getCurrentPage(), search.getPageSize());
        List<VoiceOnDemondData> voiceOnDemondDatas = voiceService.queryVoiceOnDemondDataList(page, search);

        String res = null;
        try {
            res = getQueryResult(voiceOnDemondDatas, page);
            JSONObject o = new JSONObject();
            o.put("pageCount", page.getTotalPage());
            o.put("content", res);
            return ajaxJsonSuccessMessage(o);
        } catch (Exception e) {
            LOG.error("ajaxQueryUnGoingOrder", e);
            return ajaxJsonErrorMessage(Constants.INFO_SYS_ERROR);
        }

    }

    private String getQueryResult(List<VoiceOnDemondData> voiceOnDemondDatas, PageBean page)
            throws Exception {
        initBathPath();
        HashMap map = new HashMap();
        map.put("voiceOnDemondDataList", voiceOnDemondDatas);
        map.put("page", page);
        map.put("basePath", getBasePath());

        String result = "";
        result = templateService.generateContentByFreeMarker(
                Constants.TEMPLATE_VOICEONDEMOND_DATA_QUERY_RESULT, map);
        return result;
    }

    public String ajaxAddVoiceData() {
        LOG.info("Start ArticleAction process,method is ajaxQuery");
        LOG.debug("Action is:" + search.getAction());
        //上传图片到OSS
        if (null != search.getImgUrlImage()) {
            String imgUrl = null;
            try {
                imgUrl = uploadVoiceImgUrl(search.getImgUrlImage(), search.getImgUrlImageFileName());
            } catch (Exception e) {
                LOG.error("uploadStuffIcon", e);
            }
            imgUrl = null == imgUrl ? "" : imgUrl;
            search.setImgUrl(imgUrl);

        }
        //上传音频到OSS
        if (null != search.getVoiceUrlMp3()) {

            String destPath = null;
            osInfo = (Map) request.getSession().getServletContext().getAttribute("OSMap");
            if (osInfo.get("os.name").toString().contains("Windows")) {
                destPath = PropertiesService.getString("windows.temp.path");

            } else {
                destPath = PropertiesService.getString("unix.temp.path");

            }
            File destPathFile = new File(destPath, "voice");
            destPathFile = new File(destPath, "voice");
            if (!destPathFile.exists()) {
                destPathFile.mkdirs();
            }

            File destFile = new File(destPathFile, search.getVoiceUrlMp3FileName());
            try {
                copy(search.getVoiceUrlMp3(), destFile);
            } catch (Exception e) {
                e.printStackTrace();
                destFile = null;
            }

            String voiceUrl = null;
            try {
                if (null != destFile) {
                    voiceUrl = uploadVoiceFile(destFile, search.getVoiceUrlMp3FileName());
                    voiceUrl = null == voiceUrl ? "" : voiceUrl;
                    if (!TextUtils.isEmpty(voiceUrl)) {
                        int length = getAudioLength(destFile);
                        if (length > 0) {
                            search.setEntend1(String.valueOf(length));
                        }
                    }
                }
            } catch (Exception e) {
                LOG.error("uploadStuffIcon", e);
            } finally {
                if (null != destFile) {
                    destFile.delete();
                }
            }
            search.setVoiceUrl(voiceUrl);
        }
        Date date = new Date();
        search.setCreateDate(date);
        search.setUpdateDate(date);
        search.setIsUsedFlag((short) 1);
        voiceService.addVoiceOnDemondDate(search);
        JSONObject o = new JSONObject();
        if (search.getRecid() > 0) {
            o.put("errorCode", 0);
            o.put("errorMsg", "新增成功");
        } else {
            o.put("errorCode", -1);
            o.put("errorMsg", "新增失败");
        }
        return ajaxJson(o);
    }

    public String ajaxUpdateVoiceData() {
        LOG.info("Start ArticleAction process,method is ajaxQuery");
        LOG.debug("Action is:" + search.getAction());
        //上传图片到OSS
        if (null != search.getImgUrlImage()) {
            String imgUrl = null;
            try {
                imgUrl = uploadVoiceImgUrl(search.getImgUrlImage(), search.getImgUrlImageFileName());
            } catch (Exception e) {
                LOG.error("uploadStuffIcon", e);
            }
            imgUrl = null == imgUrl ? "" : imgUrl;
            search.setImgUrl(imgUrl);

        }
        //上传音频到OSS
        if (null != search.getVoiceUrlMp3()) {

            String destPath = null;
            osInfo = (Map) request.getSession().getServletContext().getAttribute("OSMap");
            if (osInfo.get("os.name").toString().contains("Windows")) {
                destPath = PropertiesService.getString("windows.temp.path");

            } else {
                destPath = PropertiesService.getString("unix.temp.path");

            }
            File destPathFile = new File(destPath, "voice");
            destPathFile = new File(destPath, "voice");
            if (!destPathFile.exists()) {
                destPathFile.mkdirs();
            }

            File destFile = new File(destPathFile, search.getVoiceUrlMp3FileName());
            try {
                copy(search.getVoiceUrlMp3(), destFile);
            } catch (Exception e) {
                e.printStackTrace();
                destFile = null;
            }

            String voiceUrl = null;
            try {
                if (null != destFile) {
                    voiceUrl = uploadVoiceFile(destFile, search.getVoiceUrlMp3FileName());
                    voiceUrl = null == voiceUrl ? "" : voiceUrl;
                    if (!TextUtils.isEmpty(voiceUrl)) {
                        int length = getAudioLength(destFile);
                        if (length > 0) {
                            search.setEntend1(String.valueOf(length));
                        }
                    }
                }
            } catch (Exception e) {
                LOG.error("uploadStuffIcon", e);
            } finally {
                if (null != destFile) {
                    destFile.delete();
                }
            }
            search.setVoiceUrl(voiceUrl);
        }
        Date date = new Date();
        search.setUpdateDate(date);
        voiceService.uploadVoiceOnDemondDate(search);
        JSONObject o = new JSONObject();
        o.put("errorCode", 0);
        o.put("errorMsg", "修改成功");
        return ajaxJson(o);
    }

    public String ajaxQueryVoiceDataDetail() {
        VoiceOnDemondData data = voiceService.queryVoiceOnDemondDataDetail(search.getRecid());
        if (data != null) {
            JSONObject o = new JSONObject();
            o.put("data", data);
            o.put("errorCode", 0);
            return ajaxJson(o);
        } else {
            JSONObject o = new JSONObject();
            o.put("errorCode", -1);
            o.put("errorMsg", "该音频信息不存在");
            return ajaxJson(o);
        }
    }

    public String ajaxQueryVoiceDataDetailForUpdate() {

        VoiceOnDemondData data = voiceService.queryVoiceOnDemondDataDetail(search.getRecid());
        String res = null;
        try {
            res = getQueryResultForUpdae(data);
            JSONObject o = new JSONObject();
            o.put("errorCode", 0);
            o.put("content", res);
            o.put("imgUrl",data.getImgUrl());
            o.put("voiceUrl",data.getVoiceUrl());
            o.put("isIssueFlag",data.getIsIssueFlag());
            return ajaxJsonSuccessMessage(o);
        } catch (Exception e) {
            LOG.error("ajaxQueryVoiceDataDetailForUpdate", e);
            JSONObject o = new JSONObject();
            o.put("errorCode", -1);
            o.put("errorMsg", "系统错误！");
            return ajaxJson(o);
        }
    }

    private String getQueryResultForUpdae(VoiceOnDemondData voiceOnDemondData)
            throws Exception {
        initBathPath();
        HashMap map = new HashMap();
        map.put("voiceOnDemondData", voiceOnDemondData);

        String result = "";
        result = templateService.generateContentByFreeMarker(
                Constants.TEMPLATE_VOICEONDEMOND_DATA_QUERY_FORUPDATE_RESULT, map);
        return result;
    }


    /**
     * 删除音频
     */
    public String ajaxDeleteyVoiceData() {
        VoiceOnDemondData data = voiceService.queryVoiceOnDemondDataDetail(search.getRecid());
        if (data != null) {
            data.setIsUsedFlag((short) 2);
            voiceService.uploadVoiceOnDemondDate(data);
            JSONObject o = new JSONObject();
            o.put("errorCode", 0);
            o.put("errorMsg", "删除成功");
            return ajaxJson(o);
        } else {
            JSONObject o = new JSONObject();
            o.put("errorCode", -1);
            o.put("errorMsg", "该音频信息不存在");
            return ajaxJson(o);
        }
    }


    public String getVoiceSubjectDataList() {
        voiceOnDemond = voiceService.queryVoiceOnDemondDetail(search.getVoiceOnDemondId());
        return "success";
    }

    private String uploadVoiceImgUrl(File img, String fileName) {
        //后缀
        try {
            String tailSuffix = getExtension(fileName);
            String DIR = "image/voice/" + System.currentTimeMillis() + tailSuffix;
            PutObjectResult result = uploadByOss(img, DIR);
            if (null != result) {
                return DIR;
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();

        }
        return null;
    }

    private String uploadVoiceFile(File img, String fileName) {
        //后缀
        try {
            String tailSuffix = getExtension(fileName);
            String DIR = "voice/" + System.currentTimeMillis() + tailSuffix;
            PutObjectResult result = uploadByOss(img, DIR);
            if (null != result) {
                return DIR;
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();

        }
        return null;
    }

    private int getAudioLength(File file) {
        int length = -1;
        try {

            AudioFile audioFile = AudioFileIO.read(file);
            AudioHeader audioHeader = audioFile.getAudioHeader();
            if (null != audioHeader) {
                length = audioHeader.getTrackLength();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        log.info("视频时长:" + length);
        return length;
    }

    public VoiceService getVoiceService() {
        return voiceService;
    }

    public void setVoiceService(VoiceService voiceService) {
        this.voiceService = voiceService;
    }

    public TemplateService getTemplateService() {
        return templateService;
    }

    public void setTemplateService(TemplateService templateService) {
        this.templateService = templateService;
    }

    public VoiceOnDemondDataExt getSearch() {
        return search;
    }

    public void setSearch(VoiceOnDemondDataExt search) {
        this.search = search;
    }

    @Override
    public VoiceOnDemondDataExt getModel() {
        return search;
    }

    public VoiceOnDemond getVoiceOnDemond() {
        return voiceOnDemond;
    }

    public void setVoiceOnDemond(VoiceOnDemond voiceOnDemond) {
        this.voiceOnDemond = voiceOnDemond;
    }

    public static void copy(File src, File dst) throws Exception {

        InputStream in = null;
        OutputStream out = null;
        try {
            in = new BufferedInputStream(new FileInputStream(src),
                    BUFFER_SIZE);
            out = new BufferedOutputStream(new FileOutputStream(dst),
                    BUFFER_SIZE);

            byte[] buffer = new byte[BUFFER_SIZE];
            while (in.read(buffer) > 0) {
                out.write(buffer);
                out.flush();
            }
        } finally {
            if (null != in) {
                in.close();
            }
            if (null != out) {
                out.close();
            }
        }

    }

}
